<?php
namespace app\admin\service\sensitive;

use app\admin\model\User;
use app\admin\service\BaseService;
use app\admin\model\sensitive\BoxSensitiveWord;
use think\cache\driver\Redis;
use think\Db;

/**
 * 敏感词服务类
 */
class BoxSensitiveWordService extends BaseService
{
    /**
     * @var mixed
     */
    private $params;
    /**
     * @var Redis
     */
    private $redis;

    /**
     * 构造方法
     */
    public function __construct()
    {
        $this->model = new BoxSensitiveWord();
        $this->params = request()->param();
        $this->redis = new Redis(getRedisConfig());
    }

    /**
     * Desc : 获取数据列表
     * User : Steven
     * Date : 2024-05-22 18:11
     * @return array
     */
    public function getList(): array
    {
        $where = [];
        if (!empty($this->params['word'])) {
            $where[] = ['word', 'like', '%' . $this->params['word'] . '%'];
        }
        if (!empty($this->params['create_time'][0]) && !empty($this->params['create_time'][1])) {
            $where[] = ['create_time', 'between', [$this->params['create_time'][0], $this->params['create_time'][1]]];
        }
        $user = new User();
        $userList = $user->field('id,nickname')->select();
        $userList = array_column($userList->toArray(), null, 'id');

        $result = $this->model
            ->where($where)
            ->order('id desc')
            ->paginate($this->params['limit'] ?? 10)
            ->toArray();
        $result['data'] = array_map(function ($item) use ($userList) {
            $item['create_user_name'] = $userList[$item['create_user']]['nickname'] ?? '';
            return $item;
        }, $result['data']);
        return [
            'code'  => 0,
            'msg'   => 'success',
            'count' => $result['total'] ?? 0,
            'data'  => $result['data'] ?? [],
        ];
    }

    /**
     * Notes: 添加编辑敏感词
     * User: liubaoqiang
     * DateTime: 2024/11/4 14:08
     * @return array
     */
    public function edit(): array
    {
        $id = $this->params['id'] ?? 0;
        unset($this->params['s']);
        Db::startTrans();
        try {
//            $this->params['flag'] = 0;
            $word = $this->params['word'] ?? '';
            if (empty($word)) {
                throw new \Exception('请输入敏感词');
            }
            $word = explode(',', $word);
            if (empty($id)) {
                $result = $this->model->whereIn('word',$word)->select();
                $result = $result->toArray();
                $reWord = implode(',', array_column($result, 'word'));
                if (!empty($result)) {
                    throw new \Exception('敏感词: '.$reWord.' 已存在!');
                }
                //批量添加
                $allData = [];
                foreach ($word as $k => $v){
                    $allData[$k]['word'] = $v;
                    $allData[$k]['flag'] = 0;
                    $allData[$k]['create_user'] = request()->getUserId();
                }
                $this->model->insertAll($allData);
//                $this->model->insertGetId($this->params);
            } else {
                $res = $this->model->where('word', $word[0])->find();
                if($res['id'] == $id) return ['code' => -1, 'msg' => '当前数据未变动,无需保存!!!'];
                if($res['word'] == $word[0]) throw new \Exception('敏感词: '.$word[0].' 已存在!!!');
                unset($this->params['create_user_name']);
                unset($this->params['update_time']);
                unset($this->params['create_time']);
                $this->model->where('id', $id)->update($this->params);
                $this->redis->set('sensitive_word_status_new_file', 1);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => 0, 'msg' => '操作成功!'];
    }

    public function delete(): array
    {
        $id = $this->params['id'] ?? [];
        Db::startTrans();
        try {
            $this->model->where('id','in', $id)->delete();
//            $this->model->where('1','1')->update(['flag' => 0]);
            //删除sensitive.igb文件
//            $filePath = ROOT_PATH . 'extend/VicWord/blockword/sensitive.igb';
//            if (file_exists($filePath)) {
//                unlink($filePath);
//            }
            //清空文件sensitive.igb的内容
//            file_put_contents($filePath, '');
//            $this->redis->set('sensitive_word_status', 0);
            $this->redis->set('sensitive_word_status_new_file', 1);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => 0, 'msg' => '删除成功'];
    }

    /**
     * Notes: 敏感词初始化状态
     * User: liubaoqiang
     * DateTime: 2024/11/4 10:12
     * @return array
     */
    public function getRedisStatus(): array
    {
        $actionStatus = $this->redis->get('sensitive_word_status');
        if($actionStatus == 1){
            return ['code' => 0, 'msg' => '敏感词库初始化完毕!'];
        }else{
            return ['code' => -1, 'msg' => '敏感词库初始化中!'];
        }
    }

    /**
     * Notes: 执行相应操作
     * User: liubaoqiang
     * DateTime: 2024/11/5 14:46
     * @return array
     */
    public function executeScripts(): array
    {
        $reset = $this->redis->get('redis_reset_repeat_click_limit');
        if ($reset == 1) {
            return message('请勿频繁点击操作!', false);
        }
        $is_insert = $this->redis->get('sensitive_word_status_new_file');
        if($is_insert){
            $this->model->where('1','1')->update(['flag' => 0]);
        }
        $redisStatus = $this->redis->set('sensitive_word_status', 0);
        if (!$redisStatus) {
            return message('操作失败', false);
        }
        $this->redis->set('redis_reset_repeat_click_limit', 1, 5);
        return message('操作成功!');
    }



}